package net.javamine.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

/**
 * 日期时间工具类
 * 
 * @author <a href="mailto: java_lht@163.com">Lht</a>
 * @since 2012-5-23 1.create
 */
public class DateUtils {
	
	private static Logger log = Logger.getLogger(DateUtils.class);
	
	/**
	 * 获取当前日期对应的timestamp
	 * 
	 * @return Timestamp
	 */
	public static Timestamp getTimestamp() {
		return new Timestamp(System.currentTimeMillis());
	}

	/**
	 * 获取当前日期/时间  格式：yyyy-MM-dd HH:mm:ss
	 * 
	 * @return yyyy-MM-dd HH:mm:ss
	 */
	public static String getDateTime() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		return dateFormat.format(new Date());
	}
	
	/**
	 * 获取当前日期
	 * 
	 * @return 字符串格式当前日期 yyyy-MM-dd
	 */
	public static String getDate() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat.format(new Date());
	}

	
	/**
	 * 获取当前时间
	 * @return 字符串格式当前时间 HH:mm:ss
	 */
	public static String getTime() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
		return dateFormat.format(new Date());
	}
	
	/**
	 * 获取当前日期/时间
	 * @param pattern 格式
	 * @return 字符串格式的当前时间
	 */
	public static String getDateTime(String pattern) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		return dateFormat.format(new Date());
	
	}
	
	/**
	 * 根据Date获取字符串格式的日期/时间
	 * @param date 
	 * @param pattern 格式
	 * @return
	 */
	public static String getDateTime(Date date, String pattern) {
		if (date != null && StringUtils.hasText(pattern)) {
			SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
			return dateFormat.format(date);
		} else {
			return null;
		}
	}
	
	/**
	 * 将String类型日期转换为毫秒数
	 * 
	 * @param datetime
	 *            日期时间
	 * @return 相应的毫秒数
	 * @throws Exception
	 */
	public static long getLongDateTime(String datetime, String partten) {
		if (StringUtils.hasText(datetime) && StringUtils.hasText(partten)) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat(partten);
				String dt = datetime.trim();
				Date d = sdf.parse(dt);
				return d.getTime();
			} catch (Exception e) {
				ExceptionUtils.getExceptionMessage(log, e);
				return 0;
			}
		} else {
			return 0;
		}
	}

	/**
	 * 以本周为基准 获取任意一周的任意天的星期与日期
	 * 
	 * @param week
	 *            0为当前周，-1为上周，-2为上上周，1为下周，2为下下周；以此类推
	 * @return map ("2012-01-01", "周一")
	 */
	public static Map<String, String> getWeekDates(int week) {
		Map<String, String> map = new LinkedHashMap<String, String>();

		String wDay = "";
		String wDate = "";
		String mon = "";
		String day = "";

		for (int i = 0; i < 7; i++) {
			GregorianCalendar gc = new GregorianCalendar();
			gc.add(GregorianCalendar.DATE, getMondayPlus() + 7 * week + i);
			Date date = gc.getTime();
			DateFormat df = DateFormat.getDateInstance(2);

			wDay = getWeedDay(i);
			wDate = df.format(date);
			mon = wDate.split("-")[1];
			day = wDate.split("-")[2];

			if (mon.length() < 2) {
				mon = "0" + mon;
				wDate = wDate.split("-")[0] + "-" + mon + "-" + day;
			}
			if (day.length() < 2) {
				day = "0" + day;
				wDate = wDate.split("-")[0] + "-" + mon + "-" + day;
			}

			map.put(wDate, wDay);
		}
		return map;
	}

	/**
	 * 得到对应的星期
	 * 
	 * @param i
	 * @return
	 */
	private static String getWeedDay(int i) {
		switch (i) {
		case 0:
			return "周一";
		case 1:
			return "周二";
		case 2:
			return "周三";
		case 3:
			return "周四";
		case 4:
			return "周五";
		case 5:
			return "周六";
		case 6:
			return "周日";
		}
		return "";
	}

	/**
	 * 以本月为基准，得到上月 下月的每一天的日期
	 * 
	 * @param month
	 *            0为本月 -1为上月 -2为上上月 以此类推
	 * @return
	 */
	public static List<String> getMonthDates(int month) {
		String begin = "";
		String end = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<String> list = new ArrayList<String>();

		Calendar date = Calendar.getInstance();
		date.set(Calendar.DATE, 1);
		date.add(Calendar.MONTH, month);
		begin = sdf.format(date.getTime());

		date.add(Calendar.MONTH, 1);
		date.add(Calendar.DATE, -1);
		end = sdf.format(date.getTime());
		list.add(begin);
		int day = Integer.valueOf(begin.substring(begin.lastIndexOf("-") + 1));
		String sday = "";
		for (int i = 0; i < Integer.valueOf(end
				.substring(end.lastIndexOf("-") + 1)) - 1; i++) {
			day++;
			if (String.valueOf(day).length() == 1) {
				sday = "0" + day;
			} else {
				sday = String.valueOf(day);
			}
			list.add(begin.substring(0, begin.lastIndexOf("-")) + "-" + sday);
		}
		return list;
	}

	/**
	 * 获得当前日期与本周一相差的天数
	 */
	private static int getMondayPlus() {
		Calendar cd = Calendar.getInstance();
		// 获得今天是一周的第几天，星期日是第一天，星期一是第二天......
		int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
		if (dayOfWeek == 1) {
			return -6;
		} else {
			return 2 - dayOfWeek;
		}
	}

	/**
	 * 获取一个日期段中所有的星期几
	 * 
	 * @param beginDate
	 * @param endDate
	 * @param Day
	 *            1是周日...7是周六
	 * @return 如beginDate在endDate之前，返回此时间段内的指定星期几的日期。否则将返回null
	 * @throws Exception
	 */
	public static List<String> getDayOfWeekFromAnyDates(String beginDate,
			String endDate, int Day, String partten) {
		Calendar bCalendar = stringToCalendar(beginDate, partten);
		Calendar eCalendar = stringToCalendar(endDate, partten);
		if (bCalendar.before(eCalendar)) {
			try {
				List<String> list = new ArrayList<String>();
			
				while (!bCalendar.after(eCalendar)) {
					if (bCalendar.get(Calendar.DAY_OF_WEEK) == Day) {
						list.add(calendarToString(bCalendar, partten));
					}
					bCalendar.add(Calendar.DATE, +1);
				}
				return list;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 时间的字符串格式转换为Calendar
	 * 
	 * @param string
	 * @param pattern
	 * @return
	 * @throws Exception
	 */
	public static Calendar stringToCalendar(String dateTime, String pattern) {
		Calendar returnCalendar = null;
		if (StringUtils.hasText(dateTime) && StringUtils.hasText(pattern)) {
			try {
				SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
				Date date = dateFormat.parse(dateTime);
				returnCalendar = Calendar.getInstance();
				returnCalendar.setTime(date);
				return returnCalendar;
			} catch (Exception e) {
				e.printStackTrace();
				return returnCalendar;
			}
		} else {
			return returnCalendar;
		}
	}

	/**
	 * calendar格式转换为String格式
	 * 
	 * @param calendar
	 * @param pattern
	 * @return
	 */
	public static String calendarToString(Calendar calendar, String pattern) {
		String returnString = null;
		if (StringUtils.hasText(pattern) && calendar!=null) {
			Date dataTime = calendar.getTime();
			SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
			returnString = dateFormat.format(dataTime);
		}
		return returnString;
	}

	public static void main(String[] args) {
		try {
//			 long l = getLongDateTime("2012-01-02", "12:00:00",
//			 "yyyy-MM-dd hh:mm:ss");
//			 long l2 = getLongDateTime("2012-01-02 12:00:01",
//			 "yyyy-MM-dd hh:mm:ss");
//			 System.out.println(l);
//			 System.out.println(l2);
//			 Map<String, String> map = getWeekDates(-1);
//			 for (String string : map.keySet()) {
//			 System.out.println(string);
//			 }
//			List<String> list = getMonthDates(-1);
//			for (String string : list) {
//				System.out.println(string);
//			}
//			String s = getDateTime();
//			System.out.println(s);
//			System.out.println(getDate());
//			System.out.println(getTime());
//			List<String> list = getDayOfWeekFromAnyDates("2012-01-01", "2012-02-01", 2, "yyyy-MM-dd");
//			for (String string : list) {
//				System.out.println(string);
//			}
//			Calendar calendar = stringToCalendar("2012-05-24 12:00:00", "yyyy-MM-dd HH:mm:ss");
//			Calendar calendar2 = stringToCalendar("2012-05-24 12:01:00", "yyyy-MM-dd HH:mm:ss");
//			System.out.println(calendar.before(calendar2));
//			String s = calendarToString(calendar, "yyyy-MM-dd HH:mm:ss");
//			System.out.println(s);
//			System.out.println();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
